package com.yunduansing.demo.service.impl;

import com.yunduansing.demo.entity.DepartEntity;
import com.yunduansing.demo.exception.RecordExistsException;
import com.yunduansing.demo.mapper.DepartMapper;
import com.yunduansing.demo.model.common.PageRequestModel;
import com.yunduansing.demo.model.common.PageResultModel;
import com.yunduansing.demo.model.depart.DepartTreeModel;
import com.yunduansing.demo.service.DepartService;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.SelectList;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 部门表 服务实现类
 * </p>
 *
 * @author yunduansing
 * @since 2020-05-24
 */
@Service
public class DepartServiceImpl extends ServiceImpl<DepartMapper, DepartEntity> implements DepartService {
    private static final String CACHE_PREFIX="MSBOOT:DEPART:";
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private DepartMapper mapper;

    @Override
    public PageResultModel<DepartEntity> getPage(PageRequestModel model) {
        var wrapper = new QueryWrapper<DepartEntity>();
        if (!StringUtils.isEmpty(model.getKey())) {
            wrapper.or().like("name", model.getKey()).or().like("code", model.getKey());
        }
        Page<DepartEntity> page = new Page<>(model.getCurrent(), model.getPageSize());
        var data = page(page);
        return new PageResultModel<DepartEntity>(data.getTotal(), data.getRecords());
    }

    @Override
    public boolean create(DepartEntity entity) throws RecordExistsException {
        var exists = existsByNameCode(entity.getName(), entity.getCode());
        if (exists.stream().filter(x -> x.getCode().equals(entity.getCode())).count() > 0)
            throw new RecordExistsException("已存在code为：" + entity.getCode() + "的部门。");
        if (exists.stream().filter(x -> x.getName().equals(entity.getName())).count() > 0)
            throw new RecordExistsException("已存在名为为：" + entity.getName() + "的岗位。");
        return save(entity);
    }

    @Override
    public boolean update(DepartEntity entity) throws RecordExistsException {
        var exists = existsByNameCode(entity.getName(), entity.getCode());
        if (exists.stream().filter(x -> x.getCode().equals(entity.getCode()) && x.getId() != entity.getId())
                .count() > 0)
            throw new RecordExistsException("已存在code为：" + entity.getCode() + "的部门。");
        if (exists.stream().filter(x -> x.getName().equals(entity.getName()) && x.getId() != entity.getId())
                .count() > 0)
            throw new RecordExistsException("已存在名为为：" + entity.getName() + "的部门。");
        return updateById(entity);
    }

    private List<DepartEntity> existsByNameCode(String name, String code) {
        var wrapper = new QueryWrapper<DepartEntity>();
        wrapper.or().like("code", code).or().like("name", name);
        return list(wrapper);
    }

    @Override
    public List<DepartTreeModel> getTree(boolean enabled) {
        var queryWrapper=new QueryWrapper<DepartEntity>();
        if(enabled) 
            queryWrapper.eq("status", 0);
        else {
            int[] s={0,1};
            queryWrapper.in("status", s);
        }
        return generateTree(0, list(queryWrapper));
    }

    private List<DepartTreeModel> generateTree(int pid,List<DepartEntity> entities){
        var data=entities.stream().filter(x->x.getPid()==pid).collect(Collectors.toList());
        Collections.sort(data);
        var list=new ArrayList<DepartTreeModel>();
        if(data.size()>0){
            for(var item:data){
                list.add(new DepartTreeModel(item, generateTree(item.getId(),entities),""));
            }
        }
        return list;
    }
    public List<DepartEntity> getAll(){
        var cache=redisTemplate.opsForValue().get(CACHE_PREFIX+"ALL");
        if(cache!=null){
            return (List<DepartEntity>)cache;
        }
        
        var data=list();
        if(data.size()>0){
            redisTemplate.opsForValue().set(CACHE_PREFIX+"ALL", data);
        }
        return data;
    }
}
